package jp.co.cos.ittrick.channel.controller.channel;

import java.util.List;

import jp.co.cos.ittrick.channel.Constants;
import jp.co.cos.ittrick.channel.model.ApplicationModel;
import jp.co.cos.ittrick.channel.model.ChannelModel;
import jp.co.cos.ittrick.channel.model.ChapterModel;
import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.model.PreModel;
import jp.co.cos.ittrick.channel.service.ApplicationService;
import jp.co.cos.ittrick.channel.service.ChannelService;
import jp.co.cos.ittrick.channel.service.PageService;
import jp.co.cos.ittrick.channel.service.PreService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

public class PreController extends Controller {

    private ApplicationService applicationService;
    private PreService preService;
    private PageService pageService;
    private ChannelService channelService;

    private ApplicationModel applicationModel;
    private ChapterModel chapterModel;
    private ChannelModel channelModel;
    private PageModel pageModel;
    PreModel  preModel = null;

    public PreController() {
        applicationService = new ApplicationService();
        preService = new PreService();
        pageService = new PageService();
        channelService = new ChannelService();
    }

    @Override
    public Navigation run() throws Exception {

        String pre = asString("pre");

        applicationModel = applicationService.getApplicationModel();
        requestScope("applicationModel", applicationModel);

        try {
            preModel = preService.getPreByKey(Integer.valueOf(pre));
            pageModel = preModel.getPageModelRef().getModel();
        }catch(Exception e) {
            return forward("/exception/exception404");
        }

        if(pageModel == null) {
            return forward("/exception/exception404");
        }

        chapterModel = pageModel.getChapterModelRef().getModel();
        requestScope("chapterModel", chapterModel);

        channelModel = chapterModel.getCategoryModelRef().getModel().getChannelModelRef().getModel();
        requestScope("channelModel", channelModel);

        requestScope("pageModel", pageModel);
        requestScope("preModel", preModel);

        String thisPageUrl = "http://" + applicationModel.getApplicationId() + ".appspot.com/" + channelModel.getKeyString() + "/c" + chapterModel.getKeyString() + "/page" + pageModel.getKeyString() + "/pre" + preModel.getKeyString() +  ".html";
        requestScope("thisPageUrl", thisPageUrl);

        // new 記事
        List<PageModel> newPageList = pageService.getPageListOfLimit(0, Constants.PAGE_ARTICLE_LIST_LIMIT);
        requestScope("newPageList", newPageList);

        // チャンネルリスト
        List<ChannelModel> channelList = channelService.getAll();
        requestScope("channelList", channelList);

        return forward("pre.jsp");
    }
}
